package cn.edu.hnu.gpg.api;

import cn.edu.hnu.gpg.api.error.ApiError;
import cn.edu.hnu.gpg.api.error.InvalidArgumentException;
import cn.edu.hnu.gpg.api.error.NotFoundException;
import cn.edu.hnu.gpg.api.error.PermissionDeniedException;
import cn.edu.hnu.gpg.entity.Message;
import cn.edu.hnu.gpg.entity.User;
import cn.edu.hnu.gpg.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/api/message/")
public class MessageApiController {

    private final MessageService messageService;

    @Autowired
    public MessageApiController(MessageService messageService) {
        this.messageService = messageService;
    }

    @RequestMapping(value = "list_message", method = RequestMethod.GET)
    public List<Message> listMessage(HttpServletRequest request) {

        User user = ((User) request.getSession().getAttribute("user"));
        messageService.readAllReceiveMessage(user.getUserId());

        return null;
    }

    @RequestMapping(value = "{message_id}/mark_as_read", method = RequestMethod.POST)
    @ResponseBody
    public void markMessageRead(HttpServletRequest request, @PathVariable(name = "message_id") String messageIdString) throws InvalidArgumentException, NotFoundException, PermissionDeniedException {
        User user = ((User) request.getSession().getAttribute("user"));

        int messageId;
        try {
            messageId = Integer.parseInt(messageIdString);
        } catch (NumberFormatException e) {
            throw new InvalidArgumentException(new ApiError(ApiError.ErrorType.ERR_INVALID_METHOD_ARGUMENT,
                    "Argument 'message_id' is not an integer"));
        }

        Message targetMessage = messageService.findMessageById(messageId);
        if (targetMessage == null)
            throw new NotFoundException("The message specified not found");
        if (!targetMessage.getToUserId().equals(user.getUserId()))
            throw new PermissionDeniedException("The message is not to this user");

        messageService.markMessageReaded(messageId);
    }
}
